<template>
  <div class="dc-container dc-main" v-loading="loading">
    <history ref="history" :bussObject="curentRow"></history>
    <edit-form ref="editForm" :permission="permission" @save-finished="getList" @before-load="setLoad" @after-load="resetLoad"></edit-form>
    <el-container direction="horizontal">
      <!-- 外键字段查询条件左侧布局 - 公司选择器 -->
      <el-aside width="200px">
        <vxe-table ref="leftTableRef" id="leftTableRef" :data="companyOptions" :tree-config="{}" @current-change="onCompanyChange">
          <vxe-column field="name" title="公司" tree-node resizable min-width="180px" align="left" header-align="center" sortable show-overflow></vxe-column>
        </vxe-table>
      </el-aside>
      <el-main>
        <el-row :gutter="0" justify="start" align="top">
          <el-col :span="19">
            <query-tag ref="queryTag" v-model="queryEditObject"
              :moreParm="moreParm" :routerId="$route && $route.meta.routerId" :isConditionPanel="isConditionPanel"
              @queryTagPanel="onQueryTagPanel" @queryTagClick="onQueryTagClick" @search="onSearch"></query-tag>
          </el-col>
          <el-col :span="5">
            <div style="text-align: right">
              <el-button-group>
                <el-tooltip effect="dark" content="搜索">
                  <el-button @click="onSearch" type="primary" icon="Search"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="重置">
                  <el-button type="primary" icon="RefreshRight"
                    @click="isConditionPanel ? $refs.conditionPanel.reset() : $refs.queryForm.resetFields()"></el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="更多">
                  <el-button @click="onConditionPanel('query')" type="primary" icon="DArrowRight"></el-button>
                </el-tooltip>
              </el-button-group>
            </div>
          </el-col>
        </el-row>
        <condition-panel v-if="isConditionPanel" ref="conditionPanel" v-model="moreParm"
          :conditionColumns="meta.find((item) => { return item.type == 'main' }).conditionPanel"></condition-panel>
        <el-form v-if="!isConditionPanel" ref="queryForm" :model="queryData" label-width="100px">
          <el-row>
            <!-- 上级部门查询条件 -->
            <el-col :span="6">
              <el-form-item label="上级部门">
                <el-cascader v-model="queryData['department_parent_id']" :options="departmentOptions"
                  separator="/" placeholder="请选择上级部门" clearable filterable
                  :props="{ label: 'name', value: 'id', children: 'children', checkStrictly: true, emitPath: false }"
                  :style="{ width: '100%' }"></el-cascader>
              </el-form-item>
            </el-col>
            <!-- 部门名称查询条件 -->
            <el-col :span="6">
              <el-form-item label="部门名称">
                <el-input v-model="queryData['department_name']" :maxLength="128" placeholder="请输入部门名称" clearable></el-input>
              </el-form-item>
            </el-col>
            <!-- 部门编号查询条件 -->
            <el-col :span="6">
              <el-form-item label="部门编号">
                <el-input v-model="queryData['department_code']" :maxLength="64" placeholder="请输入部门编号" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="0" justify="end" align="top">
          <el-button type="primary" icon="Plus" @click="onCreate" v-show="permission.add">添加</el-button>
        </el-row>
        <!-- 部门有parent_id字段，显示为树形表格 -->
        <vxe-table ref="tableRef" :id="'tableRef_' + $route.meta.routerId"
          :data="tableData" @sort-change="onSortChange" :tree-config="{}">
          <vxe-column field="name" title="部门名称" tree-node resizable min-width="180px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="code" title="部门编号" resizable width="120px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="company.name" title="所属公司" resizable width="120px" align="left" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="director.name" title="总监" resizable width="120px" align="center" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="manager.name" title="经理" resizable width="120px" align="center" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="sort" title="排序" resizable width="80px" align="center" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column field="remarks" title="备注" resizable min-width="150px" align="left" header-align="center" show-overflow></vxe-column>
          <!-- 系统字段列 -->
          <vxe-column field="createBy" title="创建者" resizable width="120px" align="center" header-align="center" show-overflow :visible="false"></vxe-column>
          <vxe-column field="createDate" title="创建时间" resizable width="160px" align="right" header-align="center" sortable show-overflow :visible="false"></vxe-column>
          <vxe-column field="updateBy" title="更新者" resizable width="120px" align="center" header-align="center" show-overflow :visible="false"></vxe-column>
          <vxe-column field="updateDate" title="更新时间" resizable width="160px" align="right" header-align="center" sortable show-overflow></vxe-column>
          <vxe-column title="操作" resizable width="240px" fixed="right" align="left" header-align="center">
            <template #header>
              <span>操作</span>
              <OperationIcon @click="onExport" type="primary" content="导出excel文件" icon-name="Download"></OperationIcon>
              <OperationIcon @click="onSetting('tableRef')" type="primary" content="自定义列" icon-name="Setting"></OperationIcon>
            </template>
            <template #default="scope">
              <OperationIcon @click="onView(scope)" type="info" v-show="permission.view" content="查看" icon-name="View"></OperationIcon>
              <OperationIcon @click="onEdit(scope)" type="primary" v-show="permission.edit" content="编辑" icon-name="Edit"></OperationIcon>
              <!-- 有parent_id字段，显示添加下级 -->
              <OperationIcon v-show="permission.add" @click="onCreate(scope)" type="primary" content="添加下级" icon-name="CirclePlus"></OperationIcon>
              <OperationIcon @click="onCopy(scope)" type="primary" v-show="permission.add" content="复制" icon-name="DocumentCopy"></OperationIcon>
              <OperationIcon @click="onDelete(scope)" type="danger" v-show="permission.remove" content="删除" icon-name="Delete"></OperationIcon>
              <OperationIcon @click="onShowHistory(scope)" type="primary" v-show="permission.view" content="历史记录" icon-name="InfoFilled"></OperationIcon>
            </template>
          </vxe-column>
        </vxe-table>
      </el-main>
    </el-container>        
  </div>
</template>
<script>
import { validatenull } from '@/utils/validate'
// 有parent_id字段，导入treeDepartment方法 
import { treeDepartment, deleteDepartment } from '@/api/org/department'
import { listResourcePermission } from '@/api/admin/common/permission'
import History from '@/views/components/history'
import EditForm from './form'
import QueryTag from '@/views/components/queryTag'
import ConditionPanel from '@/views/components/conditionPanel'
import meta from './meta'
import MainUI from '@/views/components/mainUI'
import OperationIcon from '@/components/OperationIcon'

// 外键关联字段在查询条件中，导入接口方法
import { treeCompany } from '@/api/org/company'
import { treeDepartment as queryDepartmentTree } from '@/api/org/department'

export default {
  extends: MainUI,
  components: { History, EditForm, QueryTag, ConditionPanel, OperationIcon },
  data() {
    return {
      permission: { view: false, add: false, edit: false, remove: false, export: false },
      meta,
      queryData: {
        // 查询条件表单字段
        'department_parent_id': '', // 上级部门
        'department_name': '', // 部门名称
        'department_code': '' // 部门编号
      },
      search: {
        // 查询条件 
        params: [],
        columnName: '', // 排序字段名
        order: '', // 排序
        offset: 0,
        limit: 10
      },

      tableData: [],
      tableId: 'org_department',

      // 外键关联字段在查询条件中，定义查询条件选项
      companyOptions: [],
      departmentOptions: []
    }
  },
  computed: {},
  methods: {
    // 必须实现的方法 - 获取列表数据
    getList() {
      this.setLoad()
      /* 查询参数 和数据权限 */
      this.search.params = []
      if (this.isConditionPanel) {
        this.search.params = this.search.params.concat(this.compositeCondition())
      } else {
        // 添加左侧公司筛选条件
        if(this.queryData['department_company_id']) {
          this.search.params.push({
            columnName: 'department.company_id',
            queryType: '=',
            value: this.queryData['department_company_id']
          })
        }
        // 添加上级部门筛选条件
        if(this.queryData['department_parent_id']) {
          this.search.params.push({
            columnName: 'department.parent_id',
            queryType: '=',
            value: this.queryData['department_parent_id']
          })
        }
        // 添加部门名称筛选条件
        if(this.queryData['department_name']) {
          this.search.params.push({
            columnName: 'department.name',
            queryType: 'like',
            value: this.queryData['department_name']
          })
        }
        // 添加部门编号筛选条件
        if(this.queryData['department_code']) {
          this.search.params.push({
            columnName: 'department.code',
            queryType: 'like',
            value: this.queryData['department_code']
          })
        }
      }
      // 数据权限
      this.pushDataPermissions(this.search.params, this.$route.meta.routerId, this.tableId)
      // 调用树形查询
      treeDepartment(this.search)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.tableData = responseData.data ? responseData.data : []
          } else {
            this.showMessage(responseData)
          }
          this.resetLoad()
        })
        .catch((error) => {
          this.outputError(error)
        })
    },
    // 必须实现的方法 - 搜索
    onSearch() {
      if (this.isConditionPanel) {
        this.search.offset = 0
        this.getList()
      } else {
        this.$refs['queryForm'].validate((valid) => {
          if (valid) {
            this.search.offset = 0
            this.getList()
          } else {
            return false
          }
        })
      }
    },
    // 必须实现的方法 - 初始化
    async pageInit() {
      this.setLoad()
      try {
        this.initOptions()
        this.search.params = []
        // 数据权限
        this.pushDataPermissions(this.search.params, this.$route.meta.routerId, this.tableId)
        let [departmentRespData, permissionRespData] = await Promise.all([
          treeDepartment(this.search),
          listResourcePermission(this.$route.meta.routerId)
        ])
        if (departmentRespData.code == 100 && permissionRespData.code == 100) {
          this.tableData = departmentRespData.data ? departmentRespData.data : []
          
          this.permission.view = permissionRespData.data.find((item) => {
            return item.permission === 'department:read'
          })
          this.permission.export = permissionRespData.data.find((item) => {
            return item.permission === 'department:export'
          })

          this.permission.add = permissionRespData.data.find((item) => {
            return item.permission === 'department:create'
          })
          this.permission.edit = permissionRespData.data.find((item) => {
            return item.permission === 'department:update'
          })
          this.permission.remove = permissionRespData.data.find((item) => {
            return item.permission === 'department:delete'
          })
        } else {
          this.showMessage(permissionRespData.code != 100 ? permissionRespData : departmentRespData)
        }
        this.resetLoad()
      } catch (error) {
        this.outputError(error)
      }
    },
    // 必须实现的方法 - 打开查看模式
    onView(scope) {
      this.$refs.editForm.openView(scope.row.id)
    },
    // 必须实现的方法 - 打开新增模式 
    onCreate(scope) {
      this.$refs.editForm.openAdd(scope ? scope.row : null)
    },
    // 必须实现的方法 - 打开编辑模式
    onEdit(scope) {
      this.$refs.editForm.openEdit(scope.row.id)
    },
    // 必须实现的方法 - 打开复制模式
    onCopy(scope) {
      this.$refs.editForm.openCopy(scope.row.id)
    },
    // 必须实现的方法 - 删除记录
    onDelete(scope) {
      this.$confirm('确定删除吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.setLoad()
          deleteDepartment(scope.row)
            .then((responseData) => {
              if (responseData.code == 100) {
                this.getList()
                this.showMessage({
                  type: 'success',
                  msg: '删除成功'
                })
              } else {
                this.showMessage(responseData)
              }
              this.resetLoad()
            })
            .catch((error) => {
              this.outputError(error)
            })
        })
        .catch(() => {})
    },
    // 必须实现的方法 - 设置
    onSetting(tableRef) {
      this.$refs[tableRef].triggerCustomEvent(event)
    },
    // 必须实现的方法 - 导出
    onExport() {
      this.$refs.tableRef.exportData()
    },
    // 必须实现的方法 - 排序
    onSortChange(orderby) {
      if (validatenull(orderby.prop)) {
        this.search.columnName = ''
        this.search.order = ''
      } else {
        this.search.columnName = orderby.prop
        this.search.order = orderby.order
      }
      this.getList()
    },
    // 外键字段查询条件左侧布局 - 公司变更事件
    onCompanyChange({ newValue }) {
      this.queryData['department_company_id'] = newValue.id
      this.$nextTick(() => {
        this.getList()
        // 不得在此处调用初始化下级选项的方法
      })
    },
    // 初始化公司选项方法
    initCompanyOptions() {
      let search_List = { params: [] }
      treeCompany(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.companyOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },
    // 初始化部门选项方法
    initDepartmentOptions() {
      let search_List = { params: [] }

      // 数据过滤逻辑：根据已选公司过滤部门
      if(this.queryData['department_company_id']) {
        search_List.params.push({
          columnName: 'department.company_id',
          queryType: '=',
          value: this.queryData['department_company_id']
        })
      }

      queryDepartmentTree(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.departmentOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },
    // 初始化选项
    initOptions() {
      // 先初始化公司数据
      this.initCompanyOptions()
      
      // 当选择了公司后，初始化部门数据
      if (this.queryData['department_company_id']) {
        this.initDepartmentOptions()
      }
    }
  },
  watch: {
    // 监听公司选择变化
    'queryData.department_company_id': {
      handler(newVal, oldVal) {
        if(newVal != oldVal) {
          // 必须清空下级已选择的值
          this.queryData['department_parent_id'] = null
          // 必须清空下级选项数组
          this.departmentOptions = []
          // 只有在新值存在时才重新加载下级数据
          if (newVal) {
            // 重新加载部门数据
            this.initDepartmentOptions()
          }
        }
      }
    }    
  },
  mounted() {
    this.pageInit()
  }
}
</script> 